package com.dzm.content.filter;

import cn.hutool.core.util.StrUtil;
import com.dzm.constants.ClientConstant;
import com.dzm.constants.RedisConstant;
import com.dzm.content.config.SecurityIgnoreUrl;
import com.dzm.content.utils.ResponseUtil;
import com.dzm.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;

/**
 * 作者：Dzm
 * 时间：2024-09-13-19:41
 * 功能：
 */

@Component
public class LoginFilter implements GlobalFilter, Ordered {

    @Autowired
    private SecurityIgnoreUrl ignoreUrl;
    @Autowired
    private RedisTemplate<String , Object> redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //判断路径访问是否在白名单
        String path = request.getURI().getPath();
        if(ignoreUrl.getUrls().contains(path)) {
            return chain.filter(exchange);
        }

        String authorization = request.getHeaders().getFirst(ClientConstant.CLIENT_TOKEN_NAME);
        if(StrUtil.isBlank(authorization)) return ResponseUtil.webFluxResponseWriter(response, "用户未登录");
        String token = authorization.replaceFirst(ClientConstant.CLIENT_TOKEN_PRE, "");
        Map<String, Object> claims = JwtUtil.parseToken(token);
        String uuid = (String) claims.get("access_id");
        //通过uud判断缓存中是否有该键，从而判断用户是否登录
        Boolean hasKey = redisTemplate.hasKey(RedisConstant.LOGIN_TOKEN + uuid);
        if(hasKey) {
            return chain.filter(exchange);
        }

        //前面条件都不满足，拦截
        return ResponseUtil.webFluxResponseWriter(response, "用户未登录");
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
